home *** CD-ROM | disk | FTP | other *** search
- Path: erich.triumf.ca!bennett
- From: bennett@erich.triumf.ca (P.Bennett)
- Newsgroups: comp.lang.c
- Subject: Re: To malloc (new) or not to malloc? Clarification. Please ignore previous post.
- Date: 9 Jan 1996 12:14 PST
- Organization: TRIUMF: Tri-University Meson Facility
- Distribution: world
- Message-ID: <9JAN199612145330@erich.triumf.ca>
- References: <4ctvk3$ort@maverick.tad.eds.com> <4cua5t$dm@maverick.tad.eds.com>
- NNTP-Posting-Host: ftp.triumf.ca
- News-Software: VAX/VMS VNEWS 1.50
-
- In article <4cua5t$dm@maverick.tad.eds.com>, fignet05.darrins@eds.com (Darrin Smith) writes...
- >Why is it that you can do something like the following:
- >
- > char *x;
- >
- > x="Some really long string with no particular meaning";
- >
- >and have no problems, but can't (safely) do something like this:
- >
- > struct st1{char one[10];
- > char two[20];
- > char three[10];
- > };
- >
- > st1 *sptr; //or struct st1 *sptr in C instead of C++
- >
- > fread(sptr,sizeof(st1),1,infile);
- >
- >This caused a program I was trying to debug to crash. When I allocated
- >memory for sptr (I used sptr=new st1; but I suppose malloc would have done
- >just as well) it worked fine.
-
- If you used sptr = new st1; you were writing C++, not C.
- >
- >
- >What is going on here? Why isn't memory set aside for st1 *sptr just as
- >it is for char *x? Before I did the new (or malloc) it seemed as though
- >my program was getting written over!
-
- char *x; and st1 *sptr; both reserve space for a pointer, but do not set the
- pointers to point anywhere useful, not reserve any space for an object for the
- pointer to point to.
-
- x = "some really long string...";
- sets the pointer x to point to the location of "some really..." which will be
- somewhere in your program (and not necessarily writeable).
-
- fread(sptr, sizeof(s1), 1, infile);
- reads data from the file into the location pointed to by the _uninitialized_
- pointer sptr. This will usually have some unpleasant result :-)
-
-
- Peter Bennett VE7CEI | Vessels shall be deemed to be in sight
- Internet: bennett@triumf.ca | of one another only when one can be
- Packet: ve7cei@ve7kit.#vanc.bc.ca | observed visually from the other
- TRIUMF, Vancouver, B.C., Canada | ColRegs 3(k)
- GPS and NMEA info and programs: ftp://sundae.triumf.ca/pub/peter/index.html
-
-
-
-
-
-
-